import { contextBridge, ipcRenderer } from 'electron';

// Custom APIs for renderer
const api = {
  getTest: (name: string) => ipcRenderer.invoke('getTest', { name }),
  autoUpdate: () => ipcRenderer.invoke('autoUpdate',),
  ipcRenderer: {
    send: (channel: string, data?: any) => ipcRenderer.send(channel, data),
    on: (channel: string, func: (event: any, ...args: any[]) => void) => {
      const subscription = (_event: any, ...args: any[]) => func(_event, ...args);
      ipcRenderer.on(channel, subscription);
      return () => ipcRenderer.off(channel, subscription);
    },
    once: (channel: string, func: (event: any, ...args: any[]) => void) => {
      ipcRenderer.once(channel, (event, ...args) => func(event, ...args));
    },
  },
  logApi: {
    log: (...args: any[]) => ipcRenderer.invoke('log', ...args),
    error: (_event: any, ...args: any[]) => ipcRenderer.invoke('error', ...args),
    warn: (_event: any, ...args: any[]) => ipcRenderer.invoke('warn', ...args),
    info: (_event: any, ...args: any[]) => ipcRenderer.invoke('info', ...args),
  },
}
// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('api', api);
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.api = api
}
